package com.example.mine

import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.ContentValues
import android.content.ContentValues.TAG
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.database.sqlite.SQLiteDatabase
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import com.example.R
import com.example.login.DBHelper
import com.example.login.LogoutReceiver
import com.example.service.MyService
import java.io.File
import java.io.FileNotFoundException
import java.io.InputStream

class MineFragment : Fragment() {

    private lateinit var profileImageView: ImageView
    private lateinit var usernameTextView: TextView
    private lateinit var passwordTextView: TextView
    private lateinit var editProfileButton: Button
    private lateinit var changePasswordButton: Button
    private lateinit var dbHelper: DBHelper
    private lateinit var db: SQLiteDatabase
    private lateinit var logoutTextView: TextView
    private lateinit var logoutReceiver: LogoutReceiver

    private var photoUri: Uri? = null

    companion object {
        private const val REQUEST_IMAGE_CAPTURE = 1
        private const val REQUEST_PICK_PHOTO = 2
        private const val REQUEST_CAMERA_PERMISSION = 100
        private const val REQUEST_STORAGE_PERMISSION = 101
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_mine, container, false)
        profileImageView = view.findViewById(R.id.profileImageView)
        usernameTextView = view.findViewById(R.id.usernameTextView)
        passwordTextView = view.findViewById(R.id.passwordTextView)
        changePasswordButton = view.findViewById(R.id.changePasswordButton)
        logoutTextView = view.findViewById(R.id.logout)

        dbHelper = DBHelper(requireContext(), "test.db", null, 1)
        db = dbHelper.writableDatabase

        loadUserData()

        profileImageView.setOnClickListener {
            showImagePickerDialog()
        }

        changePasswordButton.setOnClickListener {
            showChangePasswordDialog()
        }
        logoutTextView.setOnClickListener {
            showLogoutDialog()
        }
        logoutReceiver = LogoutReceiver()
        val intentFilter = IntentFilter("com.example.test2.ACTION_LOGOUT")
        requireActivity().registerReceiver(logoutReceiver, intentFilter)

        return view
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 注销广播接收器
        requireActivity().unregisterReceiver(logoutReceiver)
    }

    private fun showLogoutDialog() {
        AlertDialog.Builder(requireContext())
            .setTitle("退出登录")
            .setMessage("确定要退出登录吗？")
            .setPositiveButton("确定") { dialog, _ ->
                // 停止Service
                val stopServiceIntent = Intent(activity, MyService::class.java)
                activity?.stopService(stopServiceIntent)
                // 发送广播
                val intent = Intent("com.example.test2.ACTION_LOGOUT")
                requireActivity().sendBroadcast(intent)
                dialog.dismiss()
            }
            .setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
            }
            .create()
            .show()
    }

    private fun loadUserData() {
        val cursor = db.query("userInfo", arrayOf("uname", "psw"), null, null, null, null, null)
        if (cursor.moveToFirst()) {
            val username = cursor.getString(cursor.getColumnIndexOrThrow("uname"))
            val password = cursor.getString(cursor.getColumnIndexOrThrow("psw"))
            usernameTextView.text = username
            passwordTextView.text = password
        }
        cursor.close()
    }

    private fun showImagePickerDialog() {
        val options = arrayOf("拍摄", "从相册中选择")
        AlertDialog.Builder(requireContext())
            .setTitle("选择")
            .setItems(options) { dialog, which ->
                when (which) {
                    0 -> checkCameraPermission()
                    1 -> checkStoragePermission()
                }
            }
            .show()
    }

    private fun checkCameraPermission() {
        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
            ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_CAMERA_PERMISSION)
        } else {
//            Log.d(TAG, "checkCameraPermission")
            openCamera()
        }
    }


    private fun checkStoragePermission() {
        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), REQUEST_STORAGE_PERMISSION)
        } else {
            openGallery()
        }
    }

    private fun openCamera() {
        val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if (takePictureIntent.resolveActivity(requireActivity().packageManager) != null) {
            // Create a file to store the image
            val photoFile = createImageFile()
            photoFile?.let {
                photoUri = FileProvider.getUriForFile(requireContext(), "com.example.mine.fileprovider", it)

                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)

                // Grant URI permissions
                takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)

                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
            }
        }
//        Log.d(TAG, "Opening camera")
    }


    private fun openGallery() {
        val pickPhotoIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(pickPhotoIntent, REQUEST_PICK_PHOTO)
    }

    private fun createImageFile(): File? {
        val storageDir = requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File.createTempFile("JPEG_${System.currentTimeMillis()}_", ".jpg", storageDir)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_IMAGE_CAPTURE -> {
                    photoUri?.let {
                        profileImageView.setImageURI(it)
                    }
                }
                REQUEST_PICK_PHOTO -> {
                    val selectedImage: Uri = data?.data ?: return
                    try {
                        val imageStream: InputStream? = requireActivity().contentResolver.openInputStream(selectedImage)
                        val selectedBitmap = BitmapFactory.decodeStream(imageStream)
                        profileImageView.setImageBitmap(selectedBitmap)
                    } catch (e: FileNotFoundException) {
                        e.printStackTrace()
                        Toast.makeText(requireContext(), "Something went wrong", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

    private fun showChangePasswordDialog() {
        val view = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_change_password, null)
        val oldPasswordEditText = view.findViewById<EditText>(R.id.oldPasswordEditText)
        val newPasswordEditText = view.findViewById<EditText>(R.id.newPasswordEditText)

        AlertDialog.Builder(requireContext())
            .setTitle("修改密码")
            .setView(view)
            .setPositiveButton("修改") { dialog, _ ->
                val oldPassword = oldPasswordEditText.text.toString()
                val newPassword = newPasswordEditText.text.toString()
                changePassword(oldPassword, newPassword)
                dialog.dismiss()
            }
            .setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
            .create()
            .show()
    }

    private fun changePassword(oldPassword: String, newPassword: String) {
        val cursor = db.query("userInfo", arrayOf("psw"), "psw=?", arrayOf(oldPassword), null, null, null)
        if (cursor.moveToFirst()) {
            val contentValues = ContentValues().apply {
                put("psw", newPassword)
            }
            db.update("userInfo", contentValues, "psw=?", arrayOf(oldPassword))
            Toast.makeText(requireContext(), "密码修改成功", Toast.LENGTH_SHORT).show()
            passwordTextView.text = newPassword
        } else {
            Toast.makeText(requireContext(), "正在使用的密码不正确", Toast.LENGTH_SHORT).show()
        }
        cursor.close()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            REQUEST_CAMERA_PERMISSION -> {
                if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    openCamera()
                } else {
                    Toast.makeText(requireContext(), "Camera permission is required", Toast.LENGTH_SHORT).show()
                }
            }
            REQUEST_STORAGE_PERMISSION -> {
                if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    openGallery()
                } else {
                    Toast.makeText(requireContext(), "Storage permission is required", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}
